package ru.spb.osll.myfit.client.dialog;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.MultiWordSuggestOracle.MultiWordSuggestion;
import ru.spb.osll.myfit.common.TextParsingTools;

import java.util.List;

public class IncludePageDialog extends InputDialog {

  private List<String> m_pageNames;

  public IncludePageDialog(DialogEventListener listener) {
    super(listener);
    setText("Enter path to include page:");
    defineItems();
  }

  public void defineItems() {
    m_cbButtonOk.setText("Include");

    m_cbButtonOk.addClickHandler(new ClickHandler() {
      public void onClick(ClickEvent event) {
        String inputText = m_suggestBox.getText().trim();
        if (!inputText.isEmpty()) {
          inputText = normalizeSeparators(inputText);
          m_listener.onOK(inputText, m_sourceEvent);
        }
        hide();
        m_sourceEvent = null;
      }
    });
  }

  private static String normalizeSeparators(String path) {
    if (!path.startsWith(TextParsingTools.ADDRESS_BAR_SEPARATOR))
      path = TextParsingTools.ADDRESS_BAR_SEPARATOR.concat(path);

    String pattern = "(" + TextParsingTools.ADDRESS_BAR_SEPARATOR_REGEX + "){2,}";
    path = path.replaceAll(pattern, TextParsingTools.ADDRESS_BAR_SEPARATOR);

    if (path.endsWith(TextParsingTools.ADDRESS_BAR_SEPARATOR))
      path = path.substring(0, path.length() - TextParsingTools.ADDRESS_BAR_SEPARATOR.length());

    return path;
  }

  public void setPageNames(List<String> names) {
    m_pageNames = names;
    defineSuggestionItems();
  }

  private void defineSuggestionItems() {
    oracle.clear();
    suggestions.clear();
    for (String name : m_pageNames) {
      oracle.add(name);
      MultiWordSuggestion suggestion = new MultiWordSuggestion(name, name);
      suggestions.add(suggestion);
    }
    oracle.setDefaultSuggestions(suggestions);
  }
}
